function $ajax({ method = "GET", url }) {
  return new Promise(function (resolve, reject) {
    // 确定何成功何时失败;
    var xhr = new XMLHttpRequest();
    xhr.open(method, url);
    xhr.addEventListener("readystatechange", function () {
      if (xhr.readyState !== 4) {
        //如果状态值,尚未变成4(未完成),则直接退出
        return;
      }
      if (xhr.status == 200) {
        // 将响应体通过resolve传递出去;
        resolve(JSON.parse(xhr.response));
      } else {
        let errInfo = {
          msg: "请求失败",
          status: "xhr.status",
        };
        reject(errInfo);
      }
    });
    xhr.send();
  });
}
class Game {
  constructor() {
    this.progress = document.querySelector("#progress");
    this.loadSuccess = true;
  }
  preloadFn(musicSrc) {
    var preload;
    // function startPreload() {
    preload = new createjs.LoadQueue(true);
    //注意加载音频文件需要调用如下代码行
    preload.installPlugin(createjs.SOUND);
    //为preloaded添加整个队列变化时展示的进度事件
    preload.addEventListener("progress", this.handleFileProgress.bind(this));
    //为preloaded添加当队列完成全部加载后触发事件
    preload.addEventListener("complete", this.loadComplete.bind(this));
    preload.addEventListener("error", this.loadErr.bind(TouchList));
    //设置最大并发连接数  最大值为10
    preload.setMaxConnections(10);
    preload.loadManifest(musicSrc);
  }
  // 当整个队列变化时展示的进度事件的处理函数
  handleFileProgress(event) {
    if (this.loadSuccess) {
      //  progress.innerText = "Loading" + Math.ceil(event.loaded * 100) + "%";
      this.progress.innerText =
        "Loading" + (event.loaded * 100).toFixed(2) + "%";
    }
  }
  //资源加载失败
  loadErr() {
    this.loadSuccess = false;
    console.log("资源加载失败");
  }
  // 处理preload添加当队列完成全部加载后触发事件
  loadComplete(event) {
    if (!this.loadSuccess) return;
    var load = document.querySelector("#load");
    // 设置定时器，当全部加载完毕后让100%停留0.4秒，提高用户体验，不至于让用户感觉不到
    window.setTimeout(() => {
      //alert("全部完全加载完成!");
      //main.style.display="none";
      load.style.transform = `translateX(-100%)`;
    }, 400);
  }
  // startPreload();

  async init() {
    //获取音乐路径
    let res = await $ajax({ url: "./data/music.json" });
    let musicData = res.sort(() => {
        return Math.random() - 0.5;
      }).slice(0, 30);
    let musicSrc = musicData.map((e) => e.audio);
    this.preloadFn(musicSrc);
    console.log(musicSrc);
  }
}
let myGame = new Game().init();
